import React, {memo, useEffect, useState} from 'react';
import {useDispatch, useSelector} from "react-redux";
import {renderRoutes} from "react-router-config";
import {Redirect} from "react-router-dom";
import {Modal} from "antd";

import Navigation from "../../components/navigation/Navigation";
import sound from "../../assets/sounds/endSound.mp3";
import {saveIsBell} from "./run/store/actionCreators";
import {navLists, navLists_cn} from "../../common/navLists";

export default memo(function Main(props) {
  const dispatch = useDispatch();
  const {isUser, isBell, isCN, isSuper} = useSelector(state => ({
    isUser: state.loginReducer.isUser,
    isBell: state.runReducer.isBell,
    isCN: state.languageReducer.isCN,
    isSuper: state.loginReducer.isSuper
  }));
  const [isShowAlert, setIsShowAlert] = useState(false);
  const [isGo, setIsGo] = useState(false);

  useEffect(() => {
    let bellDOM = document.getElementById("endSound");
    if (!bellDOM) {
      return;
    }
    isBell ? bellDOM.play() : bellDOM.pause();
    let timer = setTimeout(() => {
      bellDOM.pause();
      dispatch(saveIsBell(false));
      clearTimeout(timer);
    }, 30000);
  }, [isBell]);

  //  取消弹窗
  function isNo() {
    setIsShowAlert(false);
  }

  //  返回首页
  function isOk() {
    sessionStorage.setItem("sessionNavIndex", "0");
    setIsGo(true);
  }

  return isUser
    ? (
      <div style={{overflow: "hidden"}}>
        <Navigation isShow={setIsShowAlert} go={isGo}
                    navItem={isCN ? navLists_cn : navLists}
                    subTitle="" mainProps={props}/>
        <section className="mainContent">
          {renderRoutes(props.route.routes)}
        </section>
        {
          isShowAlert ?
            <Modal
              title=""
              visible={true}
              onOk={isOk}
              onCancel={isNo}
              okText={isCN ? "确定" : "Yes"}
              cancelText={isCN ? "取消" : "No"}
            >
              {
                <p style={{fontSize: "18px"}}>{isCN ? "你确定要离开此界面吗?" : "Are you sure you want to leave this screen?"}</p>
              }
            </Modal> : null
        }
        <audio src={sound}
               id="endSound"
               loop={true}
        />
      </div>
    )
    : (<Redirect to="/"/>);
});